package com.zhlq.auth.user.ctrl.annotation;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.zhlq.auth.user.bean.User;
import com.zhlq.auth.user.bean.UserForm;
import com.zhlq.auth.user.service.UserService;
import com.zhlq.condition.Query;
import com.zhlq.constant.CtrlConstant;
import com.zhlq.exception.CtrlException;
import com.zhlq.export.bean.Data;
import com.zhlq.export.bean.Header;
import com.zhlq.export.service.excel.ExcelExportService;
import com.zhlq.page.Page;
import com.zhlq.tips.bean.Tips;
import com.zhlq.tips.constant.TipsConstant;
import com.zhlq.util.CollectionUtil;
import com.zhlq.validator.bean.Validator;
import com.zhlq.validator.service.ValidatorService;

/**
 * @ClassName UserCtrl
 * @Description 用户控制器
 * @author ZHLQ
 * @date 2015年4月15日 上午1:21:46
 */
@Controller
public class UserCtrl {
	
	private static final String AUTH_USER_TOEDIT = "auth/user/toedit";
	private static final String AUTH_USER_CLOSE = "auth/user/close";
	private static final String AUTH_USER_OPEN = "auth/user/open";
	private static final String AUTH_USER_EDIT = "auth/user/edit";
	private static final String AUTH_USER_LOOK = "auth/user/look";
	private static final String AUTH_USER_DELETE = "auth/user/delete";
	private static final String AUTH_USER_ADD = "auth/user/add";
	private static final String AUTH_USER_TOADD = "auth/user/toadd";
	private static final String AUTH_USER_LIST = "auth/user/list";
	private static final String AUTH_USER_CLOPEN = "auth/user/clopen";
	private static final String AUTH_USER_EXPORT_CHOOSE = "auth/user/export/choose";
	private static final String AUTH_USER_EXPORT_OPTION = "auth/user/export/option";
	private static final String AUTH_USER_IMPORT_ADD = "auth/user/import/add";
	private static final String AUTH_USER_IMPORT_EDIT = "auth/user/import/edit";
	private static final String AUTH_USER_IMPORT_ADDEDIT = "auth/user/import/addedit";
	
	@Autowired
	private UserService userService;
	@Autowired
	@Qualifier("userValidator")
	private ValidatorService validatorService;

	@Autowired
	private ExcelExportService excelExportService;

	/**
	 * 列表页面
	 */
	@RequestMapping(AUTH_USER_LIST)
	public String list(HttpServletRequest request, HttpServletResponse response,
			Page page, UserForm userForm) {
		// 查询数据
		request.setAttribute(CtrlConstant.get(CtrlConstant.PAGE_RESULT), 
				userService.retrieves(new Query(userForm), page));
		request.setAttribute(CtrlConstant.get(CtrlConstant.QUERY), userForm);
		return AUTH_USER_LIST;
	}
	
	/**
	 * 跳转新增
	 */
	@RequestMapping(AUTH_USER_TOADD)
	public String toAdd(HttpServletRequest request, HttpServletResponse response) {
		return AUTH_USER_ADD;
	}
	
	/**
	 * 新增操作
	 */
	@RequestMapping(AUTH_USER_ADD)
	public String add(HttpServletRequest request, HttpServletResponse response,
			User user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.ADD), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 保存数据库
		userService.create(user);
		request.setAttribute(CtrlConstant.get(CtrlConstant.TIPS), 
				new Tips(Tips.SUCCESS, CtrlConstant.USER_LIST, CtrlConstant.ADD_SUCCESS));
		return TipsConstant.TIPS_TIPS;
	}
	
	/**
	 * 删除操作
	 */
	@RequestMapping(AUTH_USER_DELETE)
	public String delete(HttpServletRequest request, HttpServletResponse response,
			User user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.DELETE), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 删除数据
		userService.delete(userService.retrieveOne(user));
		request.setAttribute(CtrlConstant.get(CtrlConstant.TIPS), 
				new Tips(Tips.SUCCESS, CtrlConstant.USER_LIST, CtrlConstant.DELETE_SUCCESS));
		return TipsConstant.TIPS_TIPS;
	}
	
	/**
	 * 查看操作
	 */
	@RequestMapping(AUTH_USER_LOOK)
	public String look(HttpServletRequest request, HttpServletResponse response,
			User user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.LOOK), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 查询数据
		request.setAttribute(CtrlConstant.get(CtrlConstant.LOOK), userService.retrieveOne(user));
		return AUTH_USER_LOOK;
	}
	
	/**
	 * 跳转编辑
	 */
	@RequestMapping(AUTH_USER_TOEDIT)
	public String toEdit(HttpServletRequest request, HttpServletResponse response,
			User user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.TOEIDT), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 查询数据
		request.setAttribute(CtrlConstant.get(CtrlConstant.UPDATE), userService.retrieveOne(user));
		return AUTH_USER_EDIT;
	}

	/**
	 * 编辑操作
	 */
	@RequestMapping(AUTH_USER_EDIT)
	public String edit(HttpServletRequest request, HttpServletResponse response,
			User user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.EDIT), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 保存到数据库
		userService.updateNotNullStr(user);
		request.setAttribute(CtrlConstant.get(CtrlConstant.TIPS), 
				new Tips(Tips.SUCCESS, CtrlConstant.USER_LIST, CtrlConstant.UPDATE_SUCCESS));
		return TipsConstant.TIPS_TIPS;
	}

	/**
	 * 启用操作
	 */
	@RequestMapping(AUTH_USER_OPEN)
	public String open(HttpServletRequest request, HttpServletResponse response,
			User user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.OPEN), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 查询数据
		user = (User) userService.retrieveOne(user);
		// 保存到数据库
		user.setState("1");
		userService.update(user);
		request.setAttribute(CtrlConstant.get(CtrlConstant.TIPS), new Tips(Tips.SUCCESS, CtrlConstant.USER_LIST, CtrlConstant.OPEN_SUCCESS));
		return TipsConstant.TIPS_TIPS;
	}

	/**
	 * 禁用操作
	 */
	@RequestMapping(AUTH_USER_CLOSE)
	public String close(HttpServletRequest request, HttpServletResponse response,
			User user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.CLOSE), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 查询数据
		user = (User) userService.retrieveOne(user);
		// 保存到数据库
		user.setState("0");
		userService.update(user);
		request.setAttribute(CtrlConstant.get(CtrlConstant.TIPS), new Tips(Tips.SUCCESS, CtrlConstant.USER_LIST, CtrlConstant.CLOSE_SUCCESS));
		return TipsConstant.TIPS_TIPS;
	}

	/**
	 * 启用/禁用操作
	 */
	@RequestMapping(AUTH_USER_CLOPEN)
	public String clopen(HttpServletRequest request, HttpServletResponse response,
			User user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.CLOSE), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		// 查询数据
		user = (User) userService.retrieveOne(user);
		// 保存到数据库
		if(user.getState().equals("1")){
			user.setState("0");
		} else {
			user.setState("1");
		}
		userService.update(user);
		request.setAttribute(CtrlConstant.get(CtrlConstant.TIPS), new Tips(Tips.SUCCESS, CtrlConstant.USER_LIST, CtrlConstant.CLOPEN_SUCCESS));
		return TipsConstant.TIPS_TIPS;
	}

	/**
	 * 导出操作
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(AUTH_USER_EXPORT_CHOOSE)
	public String exportChoose(HttpServletRequest request, HttpServletResponse response,
			UserForm user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.EXPORT), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		Header header = userService.userToHeader(user);
		Data data = userService.userToData(user);
		try {
			excelExportService.setOutputStream(response.getOutputStream());
		} catch (IOException e) {
			throw new CtrlException();
		}
		excelExportService.writeHeader(header);
		excelExportService.writeData(data);
		try {
			response.setHeader("Content-disposition", "attachment;  filename=" + new String(("用户."+new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date())+".xls").getBytes("gb2312"), "iso8859_1"));
		} catch (UnsupportedEncodingException e) {
			throw new CtrlException();
		}
		excelExportService.close();
		return null;
	}

	/**
	 * 导出数据
	 * @throws UnsupportedEncodingException 
	 */
	@RequestMapping(AUTH_USER_EXPORT_OPTION)
	public String exportOption(HttpServletRequest request, HttpServletResponse response,
			UserForm user) {
		// 参数验证
		List<Validator> validatorResult = validatorService.validate(validatorService.get(ValidatorService.DOWNLOAD), user);
		if(!CollectionUtil.removeNull(validatorResult)){
			request.setAttribute(CtrlConstant.get(CtrlConstant.VALIDATOR_RESULT), validatorResult);
			return TipsConstant.TIPS_VALIDATOR;
		}
		Header header = userService.userToHeader(user);
		Data data = userService.listToData(user);
		try {
			excelExportService.setOutputStream(response.getOutputStream());
		} catch (IOException e) {
			throw new CtrlException();
		}
		excelExportService.writeHeader(header);
		excelExportService.writeData(data);
		try {
			response.setHeader("Content-disposition", "attachment;  filename=" + new String(("用户."+new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date())+".xls").getBytes("gb2312"), "iso8859_1"));
		} catch (UnsupportedEncodingException e) {
			throw new CtrlException();
		}
		excelExportService.close();
		return null;
	}

	/**
	 * 新增导入
	 */
	@RequestMapping(AUTH_USER_IMPORT_ADD)
	public String importAdd(HttpServletRequest request, HttpServletResponse response,
			MultipartFile file) {
		File diskFile = excelExportService.fileToDisk(file);
		Header header = new Header();
		header.add("名称");
		header.add("结果");
		Data data = new Data();
		List<User> list = userService.fileToUser(diskFile);
		if(null != list && !list.isEmpty()){
			User user;
			for(int i = 0; i < list.size(); i++){
				user = list.get(i);
				userService.create(user);
				data.add(i, user.getName(), "成功");
			}
		}
		try {
			excelExportService.setOutputStream(response.getOutputStream());
		} catch (IOException e) {
			throw new CtrlException();
		}
		excelExportService.writeHeader(header);
		excelExportService.writeData(data);
		try {
			response.setHeader("Content-disposition", "attachment;  filename=" + new String(("用户."+new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date())+".xls").getBytes("gb2312"), "iso8859_1"));
		} catch (UnsupportedEncodingException e) {
			throw new CtrlException(e);
		}
		excelExportService.close();
		return null;
	}

	/**
	 * 编辑导入
	 */
	@RequestMapping(AUTH_USER_IMPORT_EDIT)
	public String importEdit(HttpServletRequest request, HttpServletResponse response,
			MultipartFile file) {
		File diskFile = excelExportService.fileToDisk(file);
		Header header = new Header();
		header.add("名称");
		header.add("结果");
		Data data = new Data();
		List<User> list = userService.fileToUser(diskFile);
		if(null != list && !list.isEmpty()){
			User user;
			for(int i = 0; i < list.size(); i++){
				user = list.get(i);
				userService.update(user);
				data.add(i, user.getName(), "成功");
			}
		}
		try {
			excelExportService.setOutputStream(response.getOutputStream());
		} catch (IOException e) {
			throw new CtrlException();
		}
		excelExportService.writeHeader(header);
		excelExportService.writeData(data);
		try {
			response.setHeader("Content-disposition", "attachment;  filename=" + new String(("用户."+new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date())+".xls").getBytes("gb2312"), "iso8859_1"));
		} catch (UnsupportedEncodingException e) {
			throw new CtrlException(e);
		}
		excelExportService.close();
		return null;
	}

	/**
	 * 编辑导入
	 */
	@RequestMapping(AUTH_USER_IMPORT_ADDEDIT)
	public String importAddOrEdit(HttpServletRequest request, HttpServletResponse response,
			MultipartFile file) {
		File diskFile = excelExportService.fileToDisk(file);
		Header header = new Header();
		header.add("名称");
		header.add("结果");
		Data data = new Data();
		List<User> list = userService.fileToUser(diskFile);
		if(null != list && !list.isEmpty()){
			User user;
			for(int i = 0; i < list.size(); i++){
				user = list.get(i);
				userService.createOrUpdate(user);
				data.add(i, user.getName(), "成功");
			}
		}
		try {
			excelExportService.setOutputStream(response.getOutputStream());
		} catch (IOException e) {
			throw new CtrlException();
		}
		excelExportService.writeHeader(header);
		excelExportService.writeData(data);
		try {
			response.setHeader("Content-disposition", "attachment;  filename=" + new String(("用户."+new SimpleDateFormat("yyyy-MM-dd HH-mm-ss").format(new Date())+".xls").getBytes("gb2312"), "iso8859_1"));
		} catch (UnsupportedEncodingException e) {
			throw new CtrlException(e);
		}
		excelExportService.close();
		return null;
	}

}
